package com.wg.dome.repository;

import com.wg.dome.GameConstant;
import com.wg.dome.entity.user.HeroEntity;
import com.wg.core.lang.HashTable;

import java.io.Serializable;
import java.util.HashMap;

public class HeroRepositoryEx extends HeroRepository {
    private final HashMap<Serializable, HeroEntity> packMap;
    private final HashMap<Serializable, HeroEntity> fightMap;

    public HeroRepositoryEx(long playerId) {
        this.packMap = getAll(playerId, heroEntity -> heroEntity.getSzPos() == 0);
        this.fightMap = getAll(playerId, heroEntity -> heroEntity.getSzPos() > 0);
    }

    /**
     * 从背包查找
     */
    public HeroEntity getEntityFromPack(Serializable entityId) {
        return packMap.get(entityId);
    }

    /**
     * 从在出战队列中查找
     */
    public HeroEntity getEntityFromFight(Serializable entityId) {
        return fightMap.get(entityId);
    }

    /**
     * 获取空闲上阵位置
     */
    public byte getIdleSzPos() {
        boolean[] booleans = new boolean[GameConstant.FIGHT_HERO_NUMBER];
        fightMap.forEach((key, value) -> {
            if (value.getSzPos() > 0) {
                booleans[value.getSzPos() - 1] = true;
            }
        });
        for (int i = 0; i < booleans.length; i++) {
            if (!booleans[i]) {
                return (byte) (i + 1);
            }
        }
        return 0;
    }

    /**
     * 获取空闲布阵位置
     */
    public byte getIdleBzPos() {
        boolean[] booleans = new boolean[GameConstant.FIGHT_HERO_NUMBER];
        fightMap.forEach((key, value) -> {
            if (value.getSzPos() > 0 && value.getBzPos() > 0) {
                booleans[value.getBzPos() - 1] = true;
            }
        });
        for (int i = 0; i < booleans.length; i++) {
            if (!booleans[i]) {
                return (byte) (i + 1);
            }
        }
        return 0;
    }

    /**
     * 上阵位置找英雄
     */
    public HeroEntity getEntityBySzPos(byte position) {
        for (HeroEntity heroEntity : fightMap.values()) {
            if (heroEntity.getSzPos() == position) {
                return heroEntity;
            }
        }

        return null;
    }

    /**
     * 获取布阵hashtable
     */
    public HashTable[] getBzHashTables() {
        HashTable[] roleMapArray = new HashTable[fightMap.size()];
        int index = 0;
        for (HeroEntity heroEntity : fightMap.values()) {
            HashTable hashTable = new HashTable(2);
            hashTable.put((byte) 1, heroEntity.getId());
            hashTable.put((byte) 2, heroEntity.getBzPos());
            roleMapArray[index] = hashTable;
            index++;
        }
        return roleMapArray;
    }
}
